/**
 * Created by sky_wang on 2017/2/8.
 */

var data_tables_for_views = new Array();
var columnDefs = new Array();

var gridOptions = {
    columnDefs             : columnDefs,
    rowData                : [],
    datasource             : null,
    enableServerSideSorting: true,
    enableServerSideFilter : true,
    suppressCellSelection  : true,
    rowHeight              : 22,
    colWidth               : 100,
    enableFilter:           true,
    enableColResize        : true,
    enableCellExpressions  : true,
    api                    : {},
    columnApi              : {},
    rowSelection           : 'single',
    showToolPanel: true,
    toolPanelSuppressPivotMode:true,
    headerCellRenderer: headerCellRendererFunc
};

function headerCellRendererFunc(params) {
    var eHeader = document.createElement('span');
    var eTitle = document.createTextNode( params.colDef.headerName );
    eHeader.appendChild(eTitle);
    eHeader.addEventListener('click', function() {
        var dft_value = params.colDef.headerName;
        console.log(this.innerHTML);
        if ("<input type=\"text\">" == this.innerHTML) {
            var oldhtml = dft_value;
        }
        else {
            var oldhtml = this.innerHTML;
        }
        //创建新的input元素
        var newobj = document.createElement('input');
        //为新增元素添加类型
        newobj.type = 'text';
        //为新增元素添加value值
        newobj.value = oldhtml;
        //为新增元素添加光标离开事件
        //newobj.onblur = function() {
        //    eHeader.innerHTML = this.value == oldhtml ? oldhtml : this.value;
        //    console.log( this.value);
        //    //当触发时判断新增元素值是否为空，为空则不修改，并返回原有值
        //}
        newobj.addEventListener("keypress",function(event){
            console.log(this);
            if(event.keyCode == "13")
            {
                if ("" == this.value)
                {
                    eHeader.innerHTML = dft_value;
                }
                else
                {
                    eHeader.innerHTML = this.value == oldhtml ? oldhtml : this.value;

                }
                params.colDef.headerName  = eHeader.innerHTML;
            }
        }, true);

        //设置该标签的子节点为空
        this.innerHTML = '';
        //添加该标签的子节点，input对象
        this.appendChild(newobj);

        //设置选择文本的内容或设置光标位置（两个参数：start,end；start为开始位置，end为结束位置；如果开始位置和结束位置相同则就是光标位置）
        newobj.setSelectionRange(0, oldhtml.length);
        //设置获得光标
        newobj.focus();
    });

    console.log(eHeader);
    return eHeader;
}

function getColNameFromStr(str)
{
    var arr = str.split("___"); //字符分割
    if (2 ==  arr.length)
    {
        return arr[1];
    }
    return null;
}

function getTableNameFromStr(str)
{
    var arr = str.split("___"); //字符分割
    if (2 ==  arr.length)
    {
        return arr[0];
    }
    return null;
}

function getColumnsAndGroupsForViewFromDataTables (data_tables_arr, main_table_name){
    var colArr = new Array();
    for (var i = 0; i < data_tables_arr.length; i++)
    {
        var col = new Object();
        col["headerName"] = data_tables_arr[i]["name"];
        var  sub_table_detail = data_tables_arr[i]["value"];
        var  sub_column = new Array();
        for (var j = 0; j < sub_table_detail.length; j++)
        {
            var subCol  = new Object();
            subCol["headerName"] = sub_table_detail[j]["name"];
            subCol["field"] = data_tables_arr[i]["name"]+"___"+sub_table_detail[j]["name"];
            if (main_table_name == data_tables_arr[i]["name"])
            {
                subCol["hide"] = false;
            }
            else{
                subCol["hide"] = true;//true;
            }
            subCol["editable"] = true;


            //if (j==0)
            //{
            //    subCol["columnGroupShow"] = 'close';
            //}
            //else {
            //    subCol["columnGroupShow"] = 'open';
            //}
            //filterParams: {cellRenderer: countryFilterCellRenderer, cellHeight: 20, values: ['A','B','C'], newRowsAction: 'keep'}}
            subCol["filterParams"] = {newRowsAction: 'keep'};
            sub_column[j] = subCol;
        }
        col["openByDefault"] = false;
        col["children"] = sub_column;
        colArr[i] = col;
    }
    console.log(colArr);
    return colArr;
}


function getMainTablesFromDataTables (data_tables_arr){
    var tableArr = new Array();
    console.log(data_tables_arr);
    for (var i = 0; i < data_tables_arr.length; i++)
    {
        tableArr[i] = data_tables_arr[i]["name"];
    }
    //console.log(tableArr);
    return tableArr;
}


function getColumnsForViewFromGrid (data_tables_arr){
    var colArr = new Array();
    for (var i = 0; i < data_tables_arr.length; i++)
    {
        var col = new Object();
        col = data_tables_arr[i].getColDef();
        col["hide"] = false;/*  修复 后面添加列 属性无法刷新 */
        colArr[i] = col;
    }
    return colArr;
}


function  getOptionsForGridFromView(grid_options){
    var options = {
        columnDefs: null,
        rowData: null,
        enableSorting: true,
        rowGroupPanelShow: 'always'
    }
    var colsForShowArr = grid_options.columnApi.getAllDisplayedColumns();
    options.columnDefs = getColumnsForViewFromGrid(colsForShowArr);

    console.log(options);
    return options;
}
$(document).ready(function(){
    var eGridDiv = document.querySelector('#myGrid');
    new agGrid.Grid(eGridDiv, gridOptions);
    var colsQueryArr = new Array();


    $.get("/create_view/all_data_tables", function(data) {
        data_tables_for_views = JSON.parse(data);
        var ms = getMainTablesFromDataTables(data_tables_for_views);
        for (var i = 0; i < ms.length; i++) {
            $("#main_table").append("<option value='"+ms[i]+"'>"+ms[i]+"</option>");
        }

    });
    $("#submitColumnsToGrid").click(function() {
        var s_main_table_name = $("#main_table").val();
        if ('default' == s_main_table_name)
        {
            alert('please select main table');
            return;
        }
        columnDefs = getColumnsAndGroupsForViewFromDataTables(data_tables_for_views,s_main_table_name);
        gridOptions.api.setColumnDefs(columnDefs);
        gridOptions.api.rowRenderer.refreshView();

    });

    $("#createView").click(function() {
        var c_main_table_name = $("#main_table").val();
        var c_view_name =  $("input[name='txt_view_name']").val();
        console.log(c_view_name);
        if ('default' == c_main_table_name)
        {
            alert('please select main table');
            return;
        }
        if ('' == c_view_name)
        {
            alert('please input view name');
            return;
        }
        gridOptions.api.rowRenderer.refreshView();
        var colsForShowArr = gridOptions.columnApi.getAllDisplayedColumns();

        var colsForJson = new Object();
        var colsArr = new Array();
        for (var i =0; i < colsForShowArr.length; i++)
        {
            var col_i = new Object();
            col_i["key"] = getColNameFromStr(colsForShowArr[i].getColId());
            col_i["value"] = getTableNameFromStr(colsForShowArr[i].getColId());
            colsArr[i] = col_i;
        }

        colsForJson["view_name"]  = c_view_name;
        colsForJson["main_table"] = c_main_table_name;
        colsForJson["columns"]    = colsArr;
        colsForJson["query_options_ids"] = colsQueryArr;
        colsForJson["query_options_html"] =  $('#div-search').html();
        console.log(gridOptions);
        console.log( JSON.stringify(colsForJson));



        $.ajax({
            type: 'POST',
            url: "/create_view/new_view",
            data: {data:JSON.stringify(colsForJson),options:JSON.stringify(getOptionsForGridFromView(gridOptions))},
            success: function(result){
                alert(result);
            },
            error:function(xhr,status,statusText){
                console.log(xhr);
                console.log(xhr.status);
                console.log(xhr.statusText);
                alert(xhr.responseText);
            }
            //dataType: 'text'
        });
    });

    $(".alert").click(function(){
        $('.overlay').show();
        $('.overlay-center input').hide();
        $("#overlay-center-sub-id-0").hide();
        var overlay_center_sub_id_0_is_show = false;

        var colsForShowArr = gridOptions.columnApi.getAllDisplayedColumns();

        var c_value_arr = new Array();
        for (var i =0; i < colsForShowArr.length; i++)
        {
            var col_i = colsForShowArr[i].getColId();
            var col_def = colsForShowArr[i].getColDef();
            var col_name = col_def["headerName"];
            var opt = new Option(col_name,col_i);
            $('#overlay-center-column-id').append("<option value='"+col_i+"'>"+col_name+"</option>");
        }

        $('#overlay-center-column-id').change(function(e){
            $('#overlay-center-opts-id').val('default');
            if (overlay_center_sub_id_0_is_show)
            {
                $("#overlay-center-sub-id-0").pqSelect( "destroy" );
                $("#overlay-center-sub-id-0").empty();
                $("#overlay-center-sub-id-0").hide();
                overlay_center_sub_id_0_is_show = false;
            }
        });

        $('#overlay-center-opts-id').change(function(e){

            if ($('#overlay-center-column-id').val() == "default")
            {
                $('#overlay-center-opts-id').val('default');
                alert("please select coloumn first!");
            }
            else
            {
                if (overlay_center_sub_id_0_is_show)
                {
                    $("#overlay-center-sub-id-0").pqSelect( "destroy" );
                    $("#overlay-center-sub-id-0").empty();
                    $("#overlay-center-sub-id-0").hide();
                    overlay_center_sub_id_0_is_show = false;
                }
                $('.overlay-center input').hide();

                if (this.value == 'in')
                {
                    var coloumn_name = getColNameFromStr($('#overlay-center-column-id').val());
                    var table_name = getTableNameFromStr($('#overlay-center-column-id').val());
                    $.get("/create_view/all_values_of_coloumn", {coloumn:coloumn_name,table:table_name},function(data) {
                        console.log(data);
                        for (var i =0; i < data.length; i++)
                        {
                            if (null == data[i][coloumn_name])
                            {
                                continue;
                            }
                            $("#overlay-center-sub-id-0").append("<option value='"+data[i][coloumn_name]+"'>"+data[i][coloumn_name]+"</option>");
                        }

                        $("#overlay-center-sub-id-0").pqSelect({
                            multiplePlaceholder: 'Select Regions',
                            checkbox: true //adds checkbox to options
                        }).on("change", function(evt) {
                            var val = $(this).val();
                            alert(val);
                        }).pqSelect('close');
                        overlay_center_sub_id_0_is_show = true;
                    });
                }
                if (this.value == 'equal')
                {
                    $('.overlay-center-sub-1').show();
                }
                if (this.value == 'date')
                {
                    $('.overlay-center-sub-3').show();
                }
            }
        });
    })
    $(".overlay-close").click(function(){
        $('.overlay').hide();
    })

    $(".overlay-submit").click(function(){
        console.log($('#overlay-center-column-id').find("option:selected").text());
        console.log($('#overlay-center-column-id').val());
        console.log($('#overlay-center-opts-id').val());

        var queryOptId    = $('#overlay-center-column-id').val()
        var queryOptValue = new Object();
        if ($('#overlay-center-opts-id').val() == 'in')
        {
            var opts_arr = $("#overlay-center-sub-id-0").val();
            if (null == opts_arr || opts_arr.length == 0)
            {
                alert ("nothing select")
                return;
            }
            var opts_str    ="<option value='default' >---请选择---</option>";
            var optValueArr = new Array();
            for (var i =0 ; i< opts_arr.length; i++ )
            {
                opts_str += "<option value='"+opts_arr [i] +"'> "+ opts_arr [i]+"</option>"
                optValueArr[i] = opts_arr [i];
            }
            $('#div-search').append("<div><span>"
                + $('#overlay-center-column-id').find("option:selected").text()
                + "</span>"+ "<select id='"
                + queryOptId
                +"' >"
                + opts_str
                +"</select></div>");

            queryOptValue ["key"] = "in";
            queryOptValue ["value"] = optValueArr;
        }
        if ($('#overlay-center-opts-id').val() == 'equal')
        {
            $('#div-search').append("<div><span>"+
                $('#overlay-center-column-id').find("option:selected").text()
                + "</span>"+ "<input type='text' id='"
                + queryOptId
                +"' /></div>");
            queryOptValue ["key"] = "equal";;
            queryOptValue ["value"] = null;
        }
        if ($('#overlay-center-opts-id').val() == 'date')
        {
            $('#div-search').append("<div><span>"+$('#overlay-center-column-id').find("option:selected").text()
                + "</span>"+ "<input type='date' id='"
                + queryOptId
                +"' /></div>");
            queryOptValue ["key"] = "date";
            queryOptValue ["value"] = null;
        }

        var queryOpt =  new Object();
        queryOpt["key"] = queryOptId;
        queryOpt["value"] = queryOptValue;
        colsQueryArr.push(queryOpt);
        console.log(colsQueryArr);
        console.log( $('#div-search'));
        $('.overlay').hide();
    })
});